package br.com.quiz.dao;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.Query;
import org.hibernate.Session;

import br.com.quiz.domain.Aluno;
import br.com.quiz.util.HibernateUtil;

public abstract class AlunoDAO{
	
	public static void salvarOuEditarCriptografado(Aluno a){
		a.setPesSenha(DigestUtils.md2Hex( a.getPesSenha() ) );
		AbstractDAO.salvarOuEditar( a );
	}
	public static List< Aluno > listar() {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		List< Aluno > alunos = null;
		try {
			Query consulta = sessao.getNamedQuery( "Aluno.listar" );
			alunos = consulta.list();
		} catch ( RuntimeException e ) {
			throw e;
		} finally {
			sessao.close();
		}

		return alunos;
	}

	public static Aluno filtrarPorId( int aluId ) {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Aluno aluno = null;
		try {
			Query consulta = sessao.getNamedQuery( "Aluno.filtrarPorId" );
			consulta.setInteger( "aluId", aluId );
			aluno = (Aluno) consulta.uniqueResult();
		} catch ( RuntimeException e ) {
			throw e;
		} finally {
			sessao.close();
		}

		return aluno;
	}

	public static Long verificarAluno( int pesId ) {
		Session sessao = HibernateUtil.getSessionFactory().openSession();

		try {
			String hql = "select count(p.pesId) from Pessoa p where p.pesId in (select a.pesId from Aluno a where a.pesId = p.pesId) and p.pesId= " + pesId;
			Query query = sessao.createQuery( hql );
			Long quantidadesAlunosEncontrados = (Long) query.uniqueResult();

			return quantidadesAlunosEncontrados;

		} catch ( RuntimeException ex ) {
			throw ex;
		} finally {
			sessao.close();
		}
	}
}
